import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { Form, Input, Toast, Dialog } from "antd-mobile";
import { BottomBtn } from "@components";
import { createAction, callNativeApi } from "@common/utils";
import { REQUIRED_RULE, BARCODE_PARSER } from "@common/constants";
import {
  SAGA_OTHER_IN_LOAD_OPS_FORM_DATA,
  SAGA_OTHER_IN_STASH_OPS_DATA,
  SAGA_OTHER_IN_FINISH_OPS,
} from "@store/other-in/saga-types";
import {
  POP_PAGE_STACK,
  PUSH_PAGE_STACK,
  SET_SCAN_DATA,
} from "@store/global-state/action-types";
import { CLEAR_OTHER_IN_OPS_FORM_DATA } from "@store/other-in/action-types";

const Ops = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const opsFormData = useSelector((state) => state.otherIn.opsFormData);
  const currentOrder = useSelector((state) => state.otherIn.currentOrder);
  const [disabledInputQty, setDisabledInputQty] = useState(true);
  const [recLocIdx, setRecLocIdx] = useState(0);
  const [suPlaceHolder, setSuPlaceHolder] = useState("扫码获取");
  const scandata = useSelector((state) => state.globalState.scandata);

  useEffect(() => {
    let lineId = searchParams.get("id");
    dispatch(createAction(SAGA_OTHER_IN_LOAD_OPS_FORM_DATA, { lineId }));
    return () => {
      dispatch(createAction(SET_SCAN_DATA, null));
      dispatch(createAction(CLEAR_OTHER_IN_OPS_FORM_DATA));
    };
  }, []);

  useEffect(() => {
    if (opsFormData) {
      form.setFields([
        { name: "warehouseName", value: opsFormData?.lineInfo?.suName },
        { name: "orderType", value: currentOrder.type },
      ]);
      if (opsFormData?.recLoc?.length > 0) {
        setRecLocIdx(0);
        setSuPlaceHolder(opsFormData.recLoc[0].suName);
      }
    }
  }, [opsFormData]);

  const setLocFields = ({ barcode, parseResult }) => {
    let { warehouseId, locationCode, locationName } = parseResult;
    if (currentOrder.inboundSuId !== warehouseId) {
      Dialog.alert({ content: "库位与当前仓库不匹配!" });
      return;
    }
    let setFormVal = () => {
      form.setFields([
        { name: "locationBarcode", value: barcode },
        { name: "locationName", value: locationName },
        { name: "barcode", value: "" },
        { name: "itemCode", value: "" },
        { name: "itemName", value: "" },
        { name: "batchNum", value: "" },
        { name: "qty", value: "" },
        { name: "barcodeType", value: "" },
      ]);
    };
    if (
      opsFormData.recLoc.length === 0 ||
      locationCode === opsFormData.recLoc[recLocIdx].suCode
    ) {
      // 推荐库位为空或推荐库位与所扫库位相同, 直接设置表单值
      setFormVal();
    } else {
      // 推荐库位与所扫库位不同, 二次确认
      Dialog.confirm({
        content: "当前选择库位与推荐库位不一致, 是否继续?",
        onConfirm: () => setFormVal(),
      });
    }
  };

  const setItemFields = ({ barcode, barcodeType, parseResult }) => {
    let { itemCode, itemName, isUnique } = parseResult;
    if (itemCode !== opsFormData.lineInfo.itemCode) {
      Dialog.alert({ content: "扫码物料与当前单据不匹配!" });
      return;
    }

    if (
      parseResult.pkgRuleCode &&
      parseResult.pkgRuleCode !== opsFormData.lineInfo.pkgRuleCode
    ) {
      Dialog.alert({ content: "扫码物料包装与当前单据不匹配!" });
      return;
    }

    form.setFields([
      { name: "barcode", value: barcode },
      { name: "itemCode", value: itemCode },
      { name: "itemName", value: itemName },
      { name: "batchNum", value: parseResult.batchNum },
      { name: "qty", value: parseResult.qty },
      { name: "barcodeType", value: barcodeType },
    ]);

    setDisabledInputQty(isUnique);
  };

  useEffect(() => {
    if (scandata) {
      callNativeApi({
        classFullName: BARCODE_PARSER,
        action: "parse",
        params: { barcode: scandata, bizType: "OTHER_IN" },
        needNonce: false,
      })
        .then((resp) => {
          let result = resp.data ? resp.data.payload : resp.payload;
          if (result.ruleType === "LOCATION") {
            // 库位码
            setLocFields({
              barcode: scandata,
              parseResult: result,
            });
          } else if (result.ruleType === "ITEM") {
            // 物料码
            setItemFields({
              barcode: scandata,
              barcodeType: "ITEM",
              parseResult: result,
            });
          } else if (result.ruleType === "PALLET") {
            // 托码
            setItemFields({
              barcode: scandata,
              barcodeType: "PALLET",
              parseResult: result,
            });
          }
          dispatch(createAction(SET_SCAN_DATA, null));
          return;
        })
        .catch((error) => console.log(error));
    }
  }, [scandata]);

  const checkQty = async (_, value) => {
    let max = opsFormData?.lineInfo?.qty;
    if (isNaN(value)) {
      return Promise.reject("请输入数字");
    } else if (value < 1 || value > max) {
      return Promise.reject(`数量须在1-${max}之间`);
    }
    return Promise.resolve();
  };

  const handleNextLocation = () => {
    let locationName = form.getFieldValue("locationName");
    if (locationName) {
      return;
    }

    if (opsFormData?.recLoc.length > 0) {
      if (opsFormData?.recLoc.length > recLocIdx + 1) {
        setSuPlaceHolder(opsFormData.recLoc[recLocIdx + 1].suName);
        setRecLocIdx(recLocIdx + 1);
      } else {
        setSuPlaceHolder(opsFormData.recLoc[0].suName);
        setRecLocIdx(0);
      }
    }
  };

  const handleContinue = () => {
    form
      .validateFields()
      .then(() => {
        let { barcode, barcodeType, locationBarcode, qty } =
          form.getFieldValue();
        dispatch(
          createAction(SAGA_OTHER_IN_STASH_OPS_DATA, {
            orderId: currentOrder.id,
            lineId: searchParams.get("id"),
            barcode,
            locationBarcode,
            barcodeType,
            qty,
            callback: () => {
              Toast.show({
                icon: "success",
                content: "保存成功",
                maskClickable: false,
              });
              form.setFields([
                { name: "locationBarcode", value: "" },
                { name: "locationName", value: "" },
                { name: "barcode", value: "" },
                { name: "barcodeType", value: "" },
                { name: "itemCode", value: "" },
                { name: "itemName", value: "" },
                { name: "batchNum", value: "" },
                { name: "qty", value: "" },
              ]);
              setDisabledInputQty(true);
            },
          })
        );
        return;
      })
      .catch((error) => console.log(error));
  };

  const openDetails = () => {
    let path = `/app/other-in/details?lineId=${searchParams.get("id")}`;
    navigate(path);
    dispatch(createAction(PUSH_PAGE_STACK, path));
  };

  const handleFinish = () => {
    dispatch(
      createAction(SAGA_OTHER_IN_FINISH_OPS, {
        orderId: currentOrder.id,
        lineId: searchParams.get("id"),
        callback: () => {
          dispatch(createAction(POP_PAGE_STACK));
          dispatch(createAction(POP_PAGE_STACK, navigate));
        },
      })
    );
  };

  return (
    <>
      <div style={{ marginTop: "45px", marginBottom: "65px" }}>
        <Form form={form} mode="card">
          <Form.Header>基本信息</Form.Header>
          <Form.Item name="warehouseName" label="仓库">
            <Input readOnly />
          </Form.Item>
          <Form.Item name="orderType" label="单据类型">
            <Input readOnly />
          </Form.Item>
          <Form.Header />

          <Form.Header>
            <span>物料信息</span>
            <span style={{ float: "right" }}>
              累计提交数据: {opsFormData?.recordNum ? opsFormData.recordNum : 0}
              条
            </span>
          </Form.Header>
          <Form.Item
            name="locationName"
            label="库位"
            extra={<a onClick={handleNextLocation}>下一推荐库位</a>}
            rules={REQUIRED_RULE}
          >
            <Input readOnly placeholder={suPlaceHolder} />
          </Form.Item>
          <Form.Item name="barcode" label="托码/物料码" rules={REQUIRED_RULE}>
            <Input placeholder="扫码获取" readOnly />
          </Form.Item>
          <Form.Item name="itemCode" label="物料编码">
            <Input readOnly />
          </Form.Item>
          <Form.Item name="itemName" label="物料名称">
            <Input readOnly />
          </Form.Item>
          <Form.Item name="batchNum" label="批次号">
            <Input readOnly />
          </Form.Item>
          <Form.Item
            name="qty"
            label="数量"
            rules={[
              {
                validator: (rule, value, callback) =>
                  checkQty(rule, value, callback),
              },
            ]}
          >
            <Input placeholder="请扫码或输入" readOnly={disabledInputQty} />
          </Form.Item>
          <Form.Header />
        </Form>
      </div>
      <BottomBtn
        items={[
          { btnTxt: "继续", color: "danger", handler: handleContinue },
          {
            btnTxt: "明细",
            disabled: !(opsFormData?.recordNum > 0),
            handler: openDetails,
          },
          {
            btnTxt: "完成",
            color: "primary",
            disabled: !(opsFormData?.recordNum > 0),
            handler: handleFinish,
          },
        ]}
      />
    </>
  );
};

export default Ops;
